package org.ihelpuoo.orm.handler.conn;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Iterator;
import java.util.List;

import org.ihelpuoo.lang.ObjectUtils;
import org.ihelpuoo.orm.ObjectRule;
import org.ihelpuoo.orm.filter.FieldFilter;
import org.ihelpuoo.orm.handler.ObjectProcessor;
import org.ihelpuoo.orm.handler.FieldHandler;

public class ConnSaveListFieldHandler extends FieldHandler
{

	public ConnSaveListFieldHandler(ObjectProcessor beanHandler)
	{
		super(beanHandler);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void processWithoutExceptionHandle(ObjectRule br, Field f, Object conn, Object obj, FieldFilter actived, FieldFilter locked, String prefix)
			throws Exception
	{
		Method getter = ObjectUtils.getGetter(obj.getClass(),f);
		List v = (List)getter.invoke(obj,(Object[])null);
		if (null == v || v.size() == 0)
			return;

		ObjectRule subRule = processor.getManual().getRule(v.get(0).getClass());
		Iterator it = v.iterator();
		while (it.hasNext())
		{
			Object sub = it.next();
			subRule.checkDatabaseConfig((Connection)conn,sub);
			if (subRule.isNewInDB(sub))
			{
				processor.insert(subRule,conn,sub,null,null);
			}
			else
			{
				processor.update(subRule,conn,sub,null,null);
			}
		}
	}

}
